<!-- 模板，div ，el ui元素布局-->
<template>
  <div>
    <!-- 1.导航条 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>作业管理</el-breadcrumb-item>
      <el-breadcrumb-item>作业列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2.卡片视图 -->
    <el-card>
      <!-- 2.1 顶部操作 -->

      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 使用clearable属性即可得到一个可清空的输入框   clear	在点击由 clearable 属性生成的清空按钮时触发-->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="showAddDialog">添加</el-button>
          <el-button type="primary" @click="removeById(multipleSelection)"
            >删除</el-button
          >
          <el-button type="primary" @click="exportExcel()">导出</el-button>
        </el-col>
      </el-row>

      <!-- 2.2 列表区域  :data="list" -->
      <el-table
        ref="report-table"
        :data="list"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <!-- 索引列 -->
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column label="学号" prop="xh"></el-table-column>
        <el-table-column label="姓名" prop="xm"></el-table-column>
        <el-table-column label="作业名称" prop="hname"></el-table-column>
        <el-table-column label="作业链接" prop="hhref"></el-table-column>

        <!-- 关联字典   @TableField(exist = false) private Dict  dict; -->
        <el-table-column label="作业类型" prop="dict.code"> </el-table-column>
        <el-table-column label="提交时间" prop="commitTime"></el-table-column>
        <!-- 自定义列
            <template slot-scope="scope"></template>
         -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeById([scope.row.id])"
              >删除
            </el-button>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.3 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 20, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 3.弹框区域 -->

    <!-- 添加框 -->
    <el-dialog
      title="添加"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="xh">
          <el-input v-model="addForm.xh"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="addForm.xm"></el-input>
        </el-form-item>

        <el-form-item label="作业类型" prop="homeType">
          <el-select v-model="addForm.homeType" placeholder="请选择">
            <el-option
              v-for="item in zylxList"
              :key="item.id"
              :label="item.code"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="作业名称" prop="hname">
          <el-input v-model="addForm.hname"></el-input>
        </el-form-item>
        <el-form-item label="作业链接" prop="hhref">
          <el-input type="textarea" v-model="addForm.hhref"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="xh">
          <el-input v-model="editForm.xh"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="editForm.xm"></el-input>
        </el-form-item>
        <el-form-item label="作业名称" prop="hname">
          <el-input v-model="editForm.hname"></el-input>
        </el-form-item>

        <el-form-item label="作业类型" prop="homeType">
          <el-select v-model="editForm.homeType" placeholder="请选择">
            <el-option
              v-for="item in zylxList"
              :key="item.id"
              :label="item.code"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="作业链接" prop="hhref">
          <el-input type="textarea" v-model="editForm.hhref"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<!-- 行为，业务逻辑 -->
<script>
export default {
  //变量
  data() {
    return {
      //封装的查询参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },

      multipleSelection: [], //多选  id

      list: [],
      total: 0,

      zylxList: [], //作业类型字典
      addDialogVisible: false,
      addForm: {
        xh: "",
        xm: "",
        homeType: "",
        hname: "",
        hhref: "",
      },

      addFormRules: {
        xh: [
          { required: true, message: "请输入学号", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        xm: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        hname: [
          { required: true, message: "请输入作业名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        hhref: [
          { required: true, message: "请输入作业链接", trigger: "blur" },
          {
            min: 1,
            max: 150,
            message: "长度在 1 到 150 个字符",
            trigger: "blur",
          },
        ],
        homeType: [
          { required: true, message: "请选择作业类型", trigger: "blur" },
        ],
      },

      editDialogVisible: false,

      editForm: {},
      editFormRules: {
        xh: [
          { required: true, message: "请输入学号", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        xm: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        hname: [
          { required: true, message: "请输入作业名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        hhref: [
          { required: true, message: "请输入作业链接", trigger: "blur" },
          {
            min: 1,
            max: 150,
            message: "长度在 1 到 150 个字符",
            trigger: "blur",
          },
        ],
        homeType: [
          { required: true, message: "请选择作业类型", trigger: "blur" },
        ],
      },
    };
  },
  //生命函数
  created() {
    this.getList();
    this.getzylxList();
  },
  //方法
  methods: {
    ////////////////////////////////////////////导出
    exportExcel() {
      //按需加载
      import("@/assets/js/Export2Excel").then((excel) => {
        //表头
        const tHeader = ["学号", "姓名","作业名称"];
        //字段
        const filterVal = ["xh", "xm","hname"];
        //数据
        const list = this.list; //list为后台返回的json数据
        const data = this.formatJson(filterVal, list); //数据预处理
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "导出的数据", //导出表名称
        });
      });
    },

    //格式转换,不需要改动
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },

    //////////////////////////////////////////////////
    //获取字典类型
    async getzylxList() {
      const { data: res } = await this.$http.get("/dict/showdict/zylx");

      if (res.code !== 200) {
        return this.$message.error("获取列表失败！,错误信息为：" + res.msg);
      }
      console.log(res);
      this.zylxList = res.data;
      console.log(this.zylxList);
    },

    //查询  async  await
    async getList() {
      //{k1:v1,k2:v2}  ---> ?k1=v1&k2=v2    query=&pagenum=1&pagesize=10
      console.log(this.queryInfo, this.$qs.stringify(this.queryInfo));

      const { data: res } = await this.$http.post(
        "/homework/list",
        this.$qs.stringify(this.queryInfo)
      );

      console.log(res);

      // debugger

      if (res.code !== 200) {
        return this.$message.error("获取列表失败！,错误信息为：" + res.msg);
      }

      this.list = res.data.records;

      this.total = res.data.total;
    },

    //添加
    showAddDialog() {
      this.addDialogVisible = true;
    },

    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);

        if (!valid) return;

        console.log(this.addForm);

        const { data: res } = await this.$http.post(
          "/homework/save",
          this.addForm
        );

        console.log(res);

        if (res.code !== 200) {
          return this.$message.error("添加信息失败！,错误信息为：" + res.msg);
        }

        this.$message.success("添加信息成功！");

        this.addDialogVisible = false;

        this.getList();
      });
    },

    // @close="addDialogClosed"\
    addDialogClosed() {
      console.log(this.$refs); //可以获取所有带ref属性的元素
      this.$refs.addFormRef.resetFields(); //清空表单
    },

    //编辑
    async showEditDialog(id) {
      console.log(id);
      const { data: res } = await this.$http.get("/homework/info/" + id);

      console.log(res);

      if (res.code !== 200) {
        return this.$message.error("查询信息失败！");
      }

      this.editDialogVisible = true;

      this.editForm = res.data;
    },
    async update() {
      this.$refs.editFormRef.validate(async (valid) => {
        //失败跳出
        if (!valid) return;
        console.log("----",this.editForm)
        const { data: res } = await this.$http.post(
          "/homework/update",
          this.editForm
        );

        if (res.code !== 200) {
          return this.$message.error("更新信息失败！错误信息为：" + res.msg);
        }

        // 提示修改成功
        this.$message.success("更新信息成功！");
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getList();
      });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    removeById(ids) {
      console.log("-----", ids);
      if (ids.length == 0) return this.$message.error("请先选择至少一条");

      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.post("/homework/delete", ids);

          if (res.code !== 200) {
            return this.$message.error("删除信息失败！");
          }

          console.log(res);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    ////////////////////////////////////////
    // 多选,组成id数组
    handleSelectionChange(val) {
      console.log(val);
      //复制id到multipleSelection   map  [3,2,5,6,7]
      this.multipleSelection = val.map((x) => {
        return x.id;
      });
      console.log("选择的id：", this.multipleSelection);
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val; // 获取新页码
      this.getList();
    },
  },
};
</script>

<!-- css,样式scoped -->
<style scoped>
</style>
